package com.hxgis.common.service.impl;

import com.es.common.EsAggCondition;
import com.es.common.domain.EsCondition;
import com.es.common.domain.RFFM;
import com.es.common.domain.agg.Group;
import com.es.common.enums.Order;
import com.es.wrapper.DataWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hxgis.$$;
import com.hxgis.draw.contour.IsoTracer;
import com.hxgis.draw.contour.LonLatBound;
import com.hxgis.draw.contour.WContourInterpolater;
import com.hxgis.draw.contour.WContourIsoTracer;
import com.hxgis.draw.contour.bean.FloatImageDiscreteData;
import com.hxgis.draw.contour.bean.FloatInterpolateType;
import com.hxgis.draw.core.geojson.GeojsonOption;
import com.hxgis.common.base.StationCache;
import com.hxgis.common.dto.HourRangeDTO;
import com.hxgis.common.dto.Pre1hAnalyDTO;
import com.hxgis.common.dto.RainInfoAnalysDTO;
import com.hxgis.common.entity.RainHourInfo;
import com.hxgis.common.entity.Station;
import com.hxgis.common.enums.DayRangeEnum;
import com.hxgis.common.enums.SplashColorEnum;
import com.hxgis.common.parms.RangeParm;
import com.hxgis.common.repository.RainHoursInfoRepository;
import com.hxgis.common.repository.cimiss.SurfChnPreMinMapper;
import com.hxgis.common.service.RainHourService;
import com.hxgis.common.service.cimiss.CimissHttpRequest;
import com.hxgis.common.service.graph.RainStormGraph;
import com.hxgis.common.utils.CollectionUtils;
import com.hxgis.common.utils.DownFileUtil;
import com.hxgis.common.utils.ThreadPoolFactory;
import com.hxgis.common.utils.TimeUtil;
import com.hxgis.common.vo.RainHourAnaVO;
import com.hxgis.runable.ResInfoList;
import com.hxgis.task.TaskActuator;
import com.hxgis.util.MapOperation;
import lombok.extern.slf4j.Slf4j;
import org.geojson.Feature;
import org.geojson.FeatureCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import static com.hxgis.common.utils.TimeUtil.*;

@Service
@Slf4j
public class RainHourServiceImpl implements RainHourService {

    @Value("${save.colorFigPath}")
    private String colorFigPath;

    private static ExecutorService executor = ThreadPoolFactory.createThreadPoolExecutor("小时数据请求", 50);

    @Autowired
    private CimissHttpRequest request;

    @Autowired
    private RainStormGraph rainStormGraph;

    @Autowired
    private RainHoursInfoRepository rainHoursInfoRepository;

    @Autowired
    private SurfChnPreMinMapper surfChnPreMinMapper;



    /**
     * 根据年份导入小时数据
     * @param startYear
     * @param endYear
     */
    @Override
    public void saveRainHoursByYear(Integer startYear, Integer endYear) {
        //todo 保存初始基础数据开始
        for (int i = startYear; i <= endYear; i++){
            log.info("当前正保存的年是:{}",i);
            //第一步将数据存入rainday  到时候打开
            for (int j = 1; j <= 12 ; j++){
                String firstDayOfMonth = TimeUtil.getFirstDayOfMonth(i, j);
                String lastDayOfMonth = TimeUtil.getLastDayOfMonth(i, j);
                long st = System.currentTimeMillis();
                this.saveRainHours(firstDayOfMonth + "00", lastDayOfMonth + "23");
                log.info("当前保存的是{}到{}的数据用时",firstDayOfMonth,lastDayOfMonth,System.currentTimeMillis() - st);
            }
        }
    }

    @Override
    public List<RainHourInfo> queryRainHours(String startTime, String endTime, String stationNo, Integer threadSize) {

        List<RainHourInfo> rainHourInfos = new ArrayList<>();
        long st = System.currentTimeMillis();
        if (Objects.nonNull(stationNo)){
            EsCondition esCondition = EsCondition.getEsCondition();
            esCondition.gte("time",startTime).lte(endTime).LTE("rainFall",2000);
            esCondition.size(1000000);
            esCondition.eq("stationNo",stationNo);
            rainHourInfos = rainHoursInfoRepository.selectListBatch(esCondition);
            log.info("{}到{}---查询降水小时表用时:{}-----这段时间的总数据大小：{}",startTime, endTime, System.currentTimeMillis() - st, rainHourInfos.size());
        }else{
            List<Station> stations = StationCache.getStations();
            List<String> stationIds = new ArrayList<>();
            stations.stream().forEach(x -> {
                stationIds.add(x.getStationNo());
            });
            List<String>[] lists = com.hxgis.common.utils.CollectionUtils.subArrays(stationIds, 500);
            List<Map<String,Object>> teMapList = new ArrayList<Map<String, Object>>();

            //站点维度的拆分
            List<RainHourInfo> finalRainHourInfos = getRainHoursInfos(startTime, endTime, rainHourInfos, lists, teMapList,threadSize);
            log.info("{}到{}---查询降水小时表用时:{}-----这段时间的总数据大小：{}",startTime, endTime, System.currentTimeMillis() - st, finalRainHourInfos.size());
        }
        return null;
    }

    /**
     * todo 查询时段日累加
     * @param startTime
     * @param endTime
     * @param stationNo
     */
    @Override
    public List<RainHourAnaVO> queryHourAnaByTimeRange(String startTime, String endTime, String stationNo) {
        //站点基础信息
        Map<String, Station> stationInfoMap = StationCache.getStationInfoMap();
        long st = System.currentTimeMillis();
        EsAggCondition esAggCondition = EsAggCondition.getInstance();
        Group stationNoGroup = esAggCondition.Group("stationNo");
        stationNoGroup.sum("rainFall","rainFallSum").max("rainFall","maxRainFall").maxExtFields("rainFall","time");
        stationNoGroup.order(Order.DESC,"maxRainFall");
        stationNoGroup.size(10000);
        EsCondition condition = esAggCondition.getCondition();
        condition.gte("time",startTime).lte(endTime);
        condition.lte("rainFall",5000);
        if (Objects.nonNull(stationNo)){
            // todo 单站就是查看这段时间的逐小时数据
            EsCondition sigleEsCondiTion = EsCondition.getEsCondition();
            sigleEsCondiTion.eq("stationNo",stationNo);
            sigleEsCondiTion.gte("time",startTime).lte(endTime);
            sigleEsCondiTion.lte("rainFall",5000);
            sigleEsCondiTion.size(1000);
            List<RainHourInfo> rainHourInfos = rainHoursInfoRepository.selectList(sigleEsCondiTion);
            log.info("查询逐小时降水：{}",System.currentTimeMillis() - st);
            //转换返回实体
            List<RainHourAnaVO> rainHourAnaVOS = rainHourInfos.stream().map(x -> {
                return RainHourAnaVO.builder()
                        .stationNo(x.getStationNo())
                        .stationName(stationInfoMap.get(x.getStationNo()).getCity())
                        .province(stationInfoMap.get(x.getStationNo()).getProvince())
                        .river(stationInfoMap.get(x.getStationNo()).getRiver())
                        .region(stationInfoMap.get(x.getStationNo()).getRegion())
                        .lat(Double.valueOf(stationInfoMap.get(x.getStationNo()).getLat()))
                        .lon(Double.valueOf(stationInfoMap.get(x.getStationNo()).getLon()))
                        .value(Double.parseDouble(x.getRainFall().toString()) / 10)
                        .obsTime(x.getTime().toString())
                        .build();
            }).collect(Collectors.toList());
            return rainHourAnaVOS;
        }
        List<RainInfoAnalysDTO> rainInfoAnalysDTOS = rainHoursInfoRepository.selectListAgg(esAggCondition, new DataWrapper<RainInfoAnalysDTO>() {
            @Override
            public RainInfoAnalysDTO wrapper(Map<String, Object> data) {
                RainInfoAnalysDTO rainInfoAnalysDTO = new RainInfoAnalysDTO();
                rainInfoAnalysDTO.setStationNo(data.get("stationNo").toString());
                rainInfoAnalysDTO.setMaxRainFall(Double.parseDouble(data.get("maxRainFall").toString()) / 10);
                rainInfoAnalysDTO.setTime(data.get("time").toString());
                rainInfoAnalysDTO.setRainFallSum(Double.parseDouble(data.get("rainFallSum").toString()) / 10);
                return rainInfoAnalysDTO;
            }
        });
        log.info("查询任意时段累加用时：{}",System.currentTimeMillis() - st);
        //转换返回实体
        List<RainHourAnaVO> rainHourAnaVOS = rainInfoAnalysDTOS.stream().map(x -> {
            return RainHourAnaVO.builder()
                    .stationNo(x.getStationNo())
                    .stationName(stationInfoMap.get(x.getStationNo()).getCity())
                    .province(stationInfoMap.get(x.getStationNo()).getProvince())
                    .river(stationInfoMap.get(x.getStationNo()).getRiver())
                    .region(stationInfoMap.get(x.getStationNo()).getRegion())
                    .lat(Double.valueOf(stationInfoMap.get(x.getStationNo()).getLat()))
                    .lon(Double.valueOf(stationInfoMap.get(x.getStationNo()).getLon()))
                    .value(x.getRainFallSum())
                    .maxValue(x.getMaxRainFall())
                    .maxTime(x.getTime())
                    .build();
        }).collect(Collectors.toList());
        return rainHourAnaVOS;
    }

    @Override
    public String queryGeoJson(String startTime, String endTime, String flag, HttpServletResponse response) {
        List<RainHourAnaVO> rainHourAnaVOS = this.queryHourAnaByTimeRange(startTime, endTime, null);

        if (Objects.equals("1",flag)){
            DoubleSummaryStatistics stats = rainHourAnaVOS.stream().mapToDouble(x->x.getValue()).summaryStatistics();
            double[] contourValues;
            Color[] colors;

            //todo 动态色标色卡 暂时先用24小时降水
            String[] sbtColor = SplashColorEnum.getSplashColorEnum("QH_PRE_24H").getSplashColorType().split(";");
            // 色标
            double[] sbtVal = new double[sbtColor.length + 1];

            // 自定义取色标值
            sbtVal = rainStormGraph.getDoubles("", stats.getMax(), stats.getMin(), sbtVal);
            contourValues = new double[sbtColor.length - 1];
            // 色卡
            colors = new Color[sbtColor.length];
            for (int i = 0; i < colors.length; i++) {
                String[] color = sbtColor[i].split(",");
                colors[i] = new Color(Integer.parseInt(color[0]),
                        Integer.parseInt(color[1]), Integer.parseInt(color[2]));
            }
            // 删除一头一尾数据
            for (int i = 0; i < contourValues.length; i++) {
                contourValues[i] = sbtVal[i + 1];
            }

            //todo 生成色斑图新版本
            // 准备站点数据站点数据
            List<FloatImageDiscreteData> discreteData = new ArrayList<>();
            for (RainHourAnaVO rainHourAnaVO : rainHourAnaVOS) {
                FloatImageDiscreteData floatImageDiscreteData = new FloatImageDiscreteData();
                floatImageDiscreteData.setLat(Float.parseFloat(String.valueOf(rainHourAnaVO.getLat())));
                floatImageDiscreteData.setLon(Float.parseFloat(String.valueOf(rainHourAnaVO.getLon())));
                FloatInterpolateType floatInterpolateType = new FloatInterpolateType(Float.parseFloat(String.valueOf(rainHourAnaVO.getValue())));
                floatImageDiscreteData.setVal(floatInterpolateType);
                discreteData.add(floatImageDiscreteData);
            }


            //构建经纬度边界
            LonLatBound lonLatBound = LonLatBound.from(15f, 70f, 55f, 136f);
            //插值器： 离散点 -> 格点
            WContourInterpolater interpolater = new WContourInterpolater(lonLatBound, 0.05, 0.05);
//        interpolater.setNeighborMode(3);
            interpolater.setRadiusMode(0.5f,2);
            interpolater.setUndefValue(999999f);
            //等值线追踪器：格点 -> polygon(后台)/geojson(前台)
            IsoTracer isoTracer = new WContourIsoTracer(contourValues, colors);
            //生成geojson
            FeatureCollection features = isoTracer.traceForGeoJson(interpolater.convert(discreteData), GeojsonOption.getDefault());
            //白色的过滤掉
            List<Feature> filterFeatures = features.getFeatures().stream().filter((p) -> (!("#ffffff").equals(p.getProperties().get("fillColor").toString())))
                    .collect(Collectors.toList());

            FeatureCollection featureCollection = new FeatureCollection();
            featureCollection.setFeatures(filterFeatures);
            String geoJson = null;
            try {
                geoJson = new ObjectMapper().writeValueAsString(featureCollection);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return geoJson;
        }else{

            String url = null;
            try {
                String firstTitle = null;
                String secondTitle = null;

                String urlName = "全国累计小时降水";

                if (Objects.equals(startTime,endTime)){
                    secondTitle = TimeUtil.changeStyle(startTime,FORMATOR_YMDH,ZN_FORMATOR_YMDH);
                }else{
                    secondTitle = TimeUtil.changeStyle(startTime,FORMATOR_YMDH,ZN_FORMATOR_YMDH) + "到"+ TimeUtil.changeStyle(endTime,FORMATOR_YMDH,ZN_FORMATOR_YMDH);
                }
                firstTitle = urlName + "[" + "mm" + "]";
                String fileName = null;
                fileName = colorFigPath + File.separator + urlName + secondTitle + "色斑图" + ".png";

                List<Double> values  = rainHourAnaVOS.stream().map(u -> u.getValue()).collect(Collectors.toList());
                //经纬度
                List<Double> latLists = rainHourAnaVOS.stream().map(u -> u.getLat()).collect(Collectors.toList());
                List<Double> lonLists = rainHourAnaVOS.stream().map(u -> u.getLon()).collect(Collectors.toList());

                url = rainStormGraph.genColorMap(fileName, firstTitle, secondTitle, true,  "mm", 999999d, "QH_PRE_24H",
                        values, latLists, lonLists);
            } catch (Exception e) {
                e.printStackTrace();
            }
            File file = new File(url);
            if (file.exists()) {
                DownFileUtil.printFile(file, response);
                file.delete();
            }
            return null;
        }
    }


    @Override
    public Object rangeGroup(String startTime, String endTime, List<RangeParm> rangeParms) {
        EsAggCondition esAggCondition = EsAggCondition.getInstance();
        Group stationNoGroup = esAggCondition.Group("stationNo");
        stationNoGroup.sum("rainFall","rainFallSum");
        stationNoGroup.size(10000);
        /**
         * 0-30
         * 30-40
         * 40-50
         * 50-60
         * 60-100
         * >=100
         */
//        List<RFFM> rffms = new ArrayList<RFFM>(){{
//            add(new RFFM(0d, 100d,"SQPRE1").setCludeLower(true,false));
//            add(new RFFM(100d, 200d,"SQPRE2").setCludeLower(true,false));
//            add(new RFFM(200d, 300d,"SQPRE3").setCludeLower(true,false));
//            add(new RFFM(300d, 400d,"SQPRE4").setCludeLower(true,false));
//        }};
//        List<RFFM> rffms = new ArrayList<RFFM>();
//        rangeParms.stream().forEach(rangeParm -> {
//            rffms.add(new RFFM(Double.parseDouble(rangeParm.getLowValue()),
//                    Double.parseDouble(rangeParm.getUpperValue()),
//                    rangeParm.getLowValue() + rangeParm.getUpperValue())
//                    .setCludeLower(true,false));
//        });
//        RFFM[] rffms1 = rffms.toArray(new RFFM[rffms.size()]);

        RFFM[] rffms1 = this.getRffm(rangeParms);

        Group rangeSub = stationNoGroup.rangeSub("rainFall", "rainFallSubSum", rffms1);
        rangeSub.sum("rainFall","subRainSum");
        rangeSub.size(rangeParms.size());

        EsCondition condition = esAggCondition.getCondition();
        condition.gte("time",startTime).lte(endTime);
        condition.lte("rainFall",5000);
        List<Map> maps = rainHoursInfoRepository.selectListAgg(esAggCondition, Map.class);


        List<HourRangeDTO> hourRangeDTOS = rainHoursInfoRepository.selectListAgg(esAggCondition, new DataWrapper<HourRangeDTO>() {
            @Override
            public HourRangeDTO wrapper(Map<String, Object> data) {
                HourRangeDTO hourRangeDTO = new HourRangeDTO();
                hourRangeDTO.setStationNo(data.get("stationNo").toString());
                hourRangeDTO.setRangeFlag(data.get("rainFallSubSum").toString());
                hourRangeDTO.setTotleSum(Double.parseDouble(data.get("rainFallSum").toString()) / 10);
                hourRangeDTO.setRangeSum(Double.parseDouble(data.get("subRainSum").toString()) / 10);
                return hourRangeDTO;
            }
        });


        return null;
    }


    //站点维度的任务拆分
    private List<RainHourInfo> getRainHoursInfos(String startTime, String endTime, List<RainHourInfo> rainHourInfos, List<String>[] lists, List<Map<String, Object>> teMapList, Integer threadSize) {
        for (int i = 0; i < lists.length; i++) {
            //站点维度拆分
            List<String> list = lists[i];
            //时间维度的拆分
            String startDay = startTime.substring(0,8);
            String endDay = endTime.substring(0,8);
            //判断两者相差多少天
            int intervalDay = TimeUtil.getDaysBetween2Date(startDay,endDay) - 1;
            if (Objects.equals(1, intervalDay) || Objects.equals(0, intervalDay)){
                Map teMap = new MapOperation(new HashMap<String, Object>()).put("staids", lists[i])
                        .put("startTime",startTime)
                        .put("endTime",endTime)
                        .getTeMap();
                teMapList.add(teMap);
            }else{
                for (int j = 0; j <= intervalDay; j++) {
                    int jj = j;
                    if (Objects.equals(0,jj)){
                        Map teMap = new MapOperation(new HashMap<String, Object>()).put("staids", lists[i])
                                .put("startTime",startTime)
                                .put("endTime",TimeUtil.nextDay(startDay,jj) + "23")
                                .getTeMap();
                        teMapList.add(teMap);
                    }else if(Objects.equals(intervalDay,jj)){
                        Map teMap = new MapOperation(new HashMap<String, Object>()).put("staids", lists[i])
                                .put("startTime",TimeUtil.nextDay(startDay,jj) + "00")
                                .put("endTime",endTime)
                                .getTeMap();
                        teMapList.add(teMap);
                    }else{
                        Map teMap = new MapOperation(new HashMap<String, Object>()).put("staids", lists[i])
                                .put("startTime",TimeUtil.nextDay(startDay,jj) + "00")
                                .put("endTime",TimeUtil.nextDay(startDay,jj)   + "23")
                                .getTeMap();
                        teMapList.add(teMap);
                    }
                }
            }
        }
        ResInfoList<List<RainHourInfo>, String, Object> listStringObjectResInfoList = $$.exeTask(threadSize, "批量查询es",
                teMapList, new TaskActuator<List<RainHourInfo>, String, Object>() {
                    public List<RainHourInfo> actuator(Map<String, Object> params) {
                        EsCondition esCondition = EsCondition.getEsCondition();
                        esCondition.gte("time",params.get("startTime").toString())
                                .lte(params.get("endTime").toString())
                                .LTE("rainFall",2000);
                        esCondition.size(1000000);
                        List<String> stationNoIds = (List<String>) params.get("staids");
                        esCondition.in("stationNo", CollectionUtils.convertCollectionString(stationNoIds));
                        return rainHoursInfoRepository.selectList(esCondition);
                    }
                });
        List<List<RainHourInfo>> resInfoListData = listStringObjectResInfoList.getData();
        List<RainHourInfo> finalRainHourInfos = rainHourInfos;
        resInfoListData.stream().forEach(x -> {
            finalRainHourInfos.addAll(x);
        });
        return finalRainHourInfos;
    }

    /**
     * 根据时间导入小时数据入es 这里需要拆分时间时间短直接跑 长要进行时间维度的拆分 并发执行
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public List<RainHourInfo> saveRainHours(String startTime, String endTime) {
        List<Station> stations = StationCache.getStations();
        List<String> stationIds = new ArrayList<>();
        stations.stream().forEach(x -> {
            stationIds.add(x.getStationNo());
        });
        List<RainHourInfo> rainHourInfos = new CopyOnWriteArrayList<>();
        List<Future<List<RainHourInfo>>> futures = new ArrayList<>();

        String startDay = startTime.substring(0,8);
        String endDay = endTime.substring(0,8);
        //判断两者相差多少天
        int intervalDay = TimeUtil.getDaysBetween2Date(startDay,endDay) - 1;
        if (Objects.equals(1, intervalDay) || Objects.equals(0, intervalDay)){
            //说明间隔很短可以直接跑
            rainHourInfos.addAll(saveRainHoursInfos(startTime,endTime,stationIds));
        }else{
            for (int i = 0; i <= intervalDay; i++) {
                int jj = i;
                if (Objects.equals(0,jj)){
                    futures.add(executor.submit(() -> saveRainHoursInfos(startTime,TimeUtil.nextDay(startDay,jj) + "23", stationIds)));
//                    rainHourInfos.addAll(saveRainHoursInfos(startTime,TimeUtil.nextDay(startDay,jj) + "23", stationIds));

//                    System.out.println(startTime + "--------" + TimeUtil.nextDay(startDay,jj) + "23");
                }else if(Objects.equals(intervalDay,jj)){
//                    rainHourInfos.addAll(saveRainHoursInfos(TimeUtil.nextDay(startDay,jj) + "00", endTime, stationIds));
                    futures.add(executor.submit(() -> saveRainHoursInfos(TimeUtil.nextDay(startDay,jj) + "00", endTime, stationIds)));
//                    System.out.println(TimeUtil.nextDay(startDay,jj) + "00" + "--------" + endTime);
                }else{
//                    rainHourInfos.addAll(saveRainHoursInfos(TimeUtil.nextDay(startDay,jj) + "00", TimeUtil.nextDay(startDay,jj)   + "23", stationIds));
                    futures.add(executor.submit(() -> saveRainHoursInfos(TimeUtil.nextDay(startDay,jj) + "00", TimeUtil.nextDay(startDay,jj)   + "23", stationIds)));
//                    System.out.println(TimeUtil.nextDay(startDay,jj) + "00" + "--------" + TimeUtil.nextDay(startDay,jj)   + "23");
                }
            }
        }
        futures.stream().forEach(future ->{
            try {
                List<RainHourInfo> subList = future.get();
                rainHourInfos.addAll(subList);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });
        List<String> listIds = new ArrayList<>();
        rainHourInfos.stream().forEach(x -> {
            listIds.add(x.getId());
        });
        Set setIds = new HashSet(listIds);
        if (!Objects.equals(listIds.size(),setIds.size())){
            log.error("当前{}到{}的数据并发请求不准确",startTime,endTime);
        }
        return null;
    }

    /**
     * 保存小时降水 根据时间切分之后
     * @param startTime
     * @param endTime
     * @param stationIds
     * @return
     */
    private List<RainHourInfo> saveRainHoursInfos(String startTime, String endTime, List<String> stationIds) {
        List<Pre1hAnalyDTO> statSurfEleByStaID = surfChnPreMinMapper.getDataByTimeAndstationNoListThreads(startTime, endTime, stationIds);
        List<RainHourInfo> rainHourInfos = new ArrayList<>();
        if (!org.springframework.util.CollectionUtils.isEmpty(statSurfEleByStaID)){
            statSurfEleByStaID.stream().forEach(x -> {
                RainHourInfo rainHourInfo = new RainHourInfo();
                rainHourInfo.setStationNo(x.getStation_id_c());
                rainHourInfo.setRainFall(new BigDecimal(x.getPRE_1h()).multiply(new BigDecimal(10)).intValue());
                String datetime = TimeUtil.changeStyle(TimeUtil.UTCToBJTime(x.getDatetime(),TimeUtil.WEB_FORMATOR_YMDHMS), TimeUtil.WEB_FORMATOR_YMDHMS, FORMATOR_YMDH);
                rainHourInfo.setTime(Integer.parseInt(datetime));
                rainHourInfo.setYear(datetime.substring(0,4));
                rainHourInfo.setDays(datetime.substring(4,8));
                rainHourInfo.setId(x.getStation_id_c() + Long.parseLong(datetime));
                rainHourInfo.setHour(datetime.substring(8,10));
                rainHourInfos.add(rainHourInfo);
            });
        }
        //保存数据
        rainHoursInfoRepository.saveBatch(rainHourInfos);
        return rainHourInfos;
    }


    /**
     * 根据前端传的区间范围转换成对应的区间范围
     * [
     *     {
     *         "lowValue": "0",
     *         "upperValue": "10",
     *         "flag": "小雨"
     *     },
     *         {
     *         "lowValue": "10",
     *         "upperValue": "20",
     *         "flag": "中雨"
     *     },
     *         {
     *         "lowValue": "20",
     *         "upperValue": "30",
     *         "flag": "大雨雨"
     *     },
     *         {
     *         "lowValue": "30",
     *         "upperValue": "50",
     *         "flag": "暴雨"
     *     }
     * ]
     * @param rangeParms
     * @return
     */
    @Override
    public RFFM[] getRffm(List<RangeParm> rangeParms){
        List<RFFM> rffms = new ArrayList<RFFM>();
        rangeParms.stream().forEach(rangeParm -> {
            if (Objects.equals("-",rangeParm.getUpperValue())){
                rffms.add(new RFFM(Double.parseDouble(rangeParm.getLowValue()) * 10,
                        DayRangeEnum.TEDABAOYU.getUpperValue() * 10,
//                        rangeParm.getLowValue() + "_" + rangeParm.getUpperValue())
                        rangeParm.getFlag())
                        .setCludeLower(true,false));
            }else{
                rffms.add(new RFFM(Double.parseDouble(rangeParm.getLowValue()) * 10,
                        Double.parseDouble(rangeParm.getUpperValue()) * 10,
//                        rangeParm.getLowValue() + "_" + rangeParm.getUpperValue())
                        rangeParm.getFlag())
                        .setCludeLower(true,false));
            }
        });
        RFFM[] rffms1 = rffms.toArray(new RFFM[rffms.size()]);
        return rffms1;
    }
}
